package com.zk.atm.utils;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;


public class PrimaryKeyUtil {

	public static final Logger logger=Logger.getLogger(PrimaryKeyUtil.class);
	
	private static Map seq_map=new HashMap();
	
	/**
	 * @author zengqun
	 * @remark 获取表对应的序列名的主键,存放到map中，避免每次加载。
	 * @param table_name
	 * @return
	 * @throws Exception
	 */
	protected static Map getSequenceNameMapByConfigFile(String filePath) throws Exception{
		filePath=StringUtil.getPropertyValue(filePath);
		if(filePath.equals("")){
			return null;
		}
		if(seq_map!=null&&seq_map.size()>0){
			return seq_map;
		}
		Properties p=new Properties();
		InputStream in=null;
		try {
			in=PrimaryKeyUtil.class.getResourceAsStream(filePath);
		    p.load(in);
		    Enumeration enumer=p.propertyNames();
		    while(enumer.hasMoreElements()){
		    	String key=StringUtil.getPropertyValue(enumer.nextElement());
		    	String value=p.getProperty(key);
		    	//System.out.println("key="+key+",value="+value);
		    	seq_map.put(key, value);
		    }
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("getSequenceNameByTableName:读取表名-序列名配置文件异常!\r\n"+e.getMessage());
		}finally{
			if(in!=null){
				in=null;
			}
		}
		
		return seq_map;
	}
	/**
	 * @author zengqun
	 * @remark 获取表对应的序列名的主键
	 * @param table_name
	 * @return
	 * @throws Exception
	 */
	protected static String getSequenceNameByTableName(String table_name) throws Exception{
		String sequence_name="";
		table_name=StringUtil.getPropertyValue(table_name);
		if(table_name.equals("")){
			return sequence_name;
		}
		//table名字，转小写，按照配置文件中的名字去找序列
		table_name=table_name.trim().toLowerCase();
//		Properties p=new Properties();
		try {
//			InputStream in=PrimaryKeyUtil.class.getResourceAsStream("/primary_key.properties");
//		    p.load(in);
//		    sequence_name=(String) p.get(table_name);
//		    if(logger.isDebugEnabled()){
//		      System.out.println(sequence_name);
//		    }
			Map seqMap=PrimaryKeyUtil.getSequenceNameMapByConfigFile("/primary_key.properties");
			return StringUtil.getPropertyValue(seqMap.get(table_name));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("getSequenceNameByTableName:读取表名-序列名配置文件异常!\r\n"+e.getMessage());
		}
		
		return sequence_name;
	}
	
	/**
	 * @author zengqun
	 * @remark 根据表对应的：序列名，获取主键值
	 * @param table_name
	 * @return
	 * @throws Exception
	 */
	protected static String getSequencePrimaryKeyValue(String sequence_name,
			Map map) throws Exception {
		sequence_name = StringUtil.getPropertyValue(sequence_name);
		if(map==null){
			map=new HashMap();
		}
		Connection conn=(Connection) map.get(ConstantsAtmp.ATMP_CONNECTION_NAME);
		long index = 0;
		try {
			if(conn==null||conn.isClosed()){
			  conn=AccessDBConnection.getConnection();
			}
			String sql = "select " + sequence_name + ".nextval from dual";
			PreparedStatement statement = conn.prepareStatement(sql);
			ResultSet rs = statement.executeQuery();
			while (rs.next()) {
				index = rs.getLong(1);
			}
			if(logger.isDebugEnabled()){
				   System.out.println("********************index="+index);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("getSequencePrimaryKeyValue:获取主键异常！\r\n"+e.getMessage());
		}finally{
			AccessDBConnection.closeConnection(conn);
		}
		return index + "";
	}
	
	/**
	 * @author zengqun
	 * @remark 根据表对应的：序列名，获取主键值
	 * @param table_name
	 * @return
	 * @throws Exception
	 * @date 2012-9-25
	 * @version 1.0
	 */
	public static synchronized String getPrimaryKey(String table_name,Map map) throws Exception{
		String primary_key="";
		String message="获取主键异常！";
		try {
			String seq_name=getSequenceNameByTableName(table_name);
			if(seq_name.equals("")){
				System.out.println(message);
				logger.error(table_name+",找不到对应的序列配置：getPrimaryKey:"+message+"\r\n");
				return primary_key;
			}
			primary_key=getSequencePrimaryKeyValue(seq_name, map);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("getPrimaryKey:"+message+"\r\n");
		}
	    return primary_key;
	}
	
	public static void main(String[] args) {
		try {
//			String seq_name=PrimaryKeyUtil.getSequenceNameByTableName("atmp_device_status_original");
//			if(seq_name.equals("")){
//				System.out.println("生成主键异常！");
//				return ;
//			}
//			PrimaryKeyUtil.getSequencePrimaryKeyValue(seq_name, null);
			//PrimaryKeyUtil.getSequencePrimaryKeyValue("seq_atmp_device", null);
			PrimaryKeyUtil.getSequenceNameMapByConfigFile("/primary_key.properties");
			StringUtil.printMap(seq_map);
			System.out.println(PrimaryKeyUtil.getPrimaryKey("atmp_device", null));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
